import os.path

from django import forms
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

from day2 import settings
from wepapi.models import File, FileModal
from wepapi.utils import form
from wepapi.utils.Pagination import Pagination
from wepapi.utils.bootstrap import BootStrapForm, BootStrapModelForm


def upload_list(request):
    if request.method == 'GET':
        return render(request, 'upload_list.html')

    if request.method == 'POST':
        # <QueryDict: {'csrfmiddlewaretoken': ['wJyBVd7hX5Q64SO8G5lUfMc8M42hvLEZNA5ix9FmFXS91EnXSSmjEyEwM4wL7UJe'], 'username': ['111']}>
        # <MultiValueDict: {'avatar': [<InMemoryUploadedFile: 1.png (image/png)>]}>
        print(request.POST)
        print(request.FILES)
        file_object = request.FILES.get('avatar')
        print(file_object)
        f = open(file_object.name, 'wb+')
        for chunk in file_object.chunks():
            f.write(chunk)
        f.close()

        result = {
            'status': True,
            'code': 200
        }
        return JsonResponse(result)


class UploadForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']
    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')


class UploadModelForm(BootStrapModelForm):

    bootstrap_exclude_fields = ['img']
    class Meta:
        model = FileModal
        fields = '__all__'

    pass


def upload_form(request):
    title = 'Form上传'
    if request.method == 'GET':
        form = UploadForm()
        fileList = File.objects.all()

        page_object = Pagination(request, fileList)
        context = {
            'title': title,
            'uform': form,
            "queryset": page_object.page_queryset,  # 分完页的数据
            "page_string": page_object.html(),  # 生成页码
        }

        return render(request, 'upload_form.html', context)

    form = UploadForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # {'name': '11', 'age': 222, 'img': <InMemoryUploadedFile: 1.png (image/png)>}
        # 1.读取图片内容，写入到文件夹中获取文件的路径
        image_object = form.cleaned_data['img']
        # fill_path='img/{}'.format(image_object.name)
        # media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        media_path = os.path.join('media', image_object.name)
        f = open(media_path, mode='wb+')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()
        # 2.将图片文件路径写入数据库
        File.objects.create(name=form.cleaned_data['name'],
                            age=form.cleaned_data['age'],
                            img=media_path)

        return HttpResponse('.....')
    return render(request, 'upload_form.html', {'title': title, 'uform': form})


def upload_modal_form(request):
    """上传文件和数据 ModalForm"""
    title = 'ModalForm上传'
    form = UploadModelForm()
    context = {
        'title': title,
        'uform': form,
        # "queryset": page_object.page_queryset,  # 分完页的数据
        # "page_string": page_object.html(),  # 生成页码
    }
    if request.method == 'GET':
        return render(request, 'upload_modal_form.html', context)

    uform = UploadModelForm(data=request.POST, files=request.FILES)
    if uform.is_valid():
        # 对于文件：自动保存
        # 字段 + 上传路径写入到数据库
        uform.save()

    return render(request, 'upload_modal_form.html', context)